<template>
	<div class="layout-pd">
		<zh-space>
			<zh-card title="">
				<zh-form ref="articleQueryForm" :model="state.queryParam">
					<zh-form-input prop="title" label="标题" placeholder="支持模糊查询" v-model="state.queryParam.title"></zh-form-input>
          <zh-form-select prop="articleStatus" label="发布状态" :options="state.dictData.ARTICLESTATUS" v-model="state.queryParam.articleStatus"></zh-form-select>
					<zh-form-select
              prop="appId"
              :lazy="true"
              label="所属应用"
              v-model="state.queryParam.appId"
              :fieldNames="{ label: 'appName', value: 'appId' }"
              funcCode="application0012"
              searchField="appName"
            ></zh-form-select>
            <zh-form-select prop="articleType" label="文章类型" :options="state.dictData.articleType" v-model="state.queryParam.articleType" :disabled="state.articleTypeDisabled" ></zh-form-select>
            <zh-form-select prop="showPosition" label="显示位置" :options="state.dictData.showPosition" v-model="state.queryParam.showPosition"></zh-form-select>
            
          <template v-if="state.advanced">
						<zh-form-select prop="fileType" label="文件类型" :options="state.dictData.fileType" v-model="state.queryParam.fileType"></zh-form-select>
            <zh-form-select prop="contentType" label="内容类型" :options="state.dictData.contentType" v-model="state.queryParam.contentType"></zh-form-select>
            <zh-form-select prop="topFlag" label="是否置顶" :options="state.dictData.flag" v-model="state.queryParam.topFlag"></zh-form-select>
            <zh-form-select prop="authStatus" label="审核状态" :options="state.dictData.authStatus" v-model="state.queryParam.authStatus"></zh-form-select>
            <zh-form-choose-org prop="orgId" label="所属组织" v-model="state.queryParam.orgId"></zh-form-choose-org>
            <zh-form-cascader
              prop="areaCode"
              label="行政区划"
              placeholder="请选择"
              v-model="state.queryParam.areaCode"
              :props="{checkStrictly: true,emitPath:false}"
              :options="state.areaCodeSelectTreeData"
            ></zh-form-cascader>
            
					</template>
					<zh-form-query v-model="state.advanced" :form-ref="articleQueryForm" :table-ref="articleListTable">
            <zh-button style="margin-left: 8px" button-type="add" @click="addArticle" v-func:article0004> 新增 </zh-button>
          </zh-form-query>
				</zh-form>
			</zh-card>
			<zh-table
				ref="articleListTable"
				funcCode="article0007"
				:columns="state.tableColumn"
				:disabled="false"
				highlight-current-row
			>
        <template #authStatus_default="{ row }">
          <zh-badge status="processing" :text="row.authStatusName" v-if="row.authStatus === '0'" />
          <zh-badge status="success" :text="row.authStatusName" v-if="row.authStatus === '1'" />
          <zh-badge color="red" :text="row.authStatusName" v-if="row.authStatus === '2'" />
        </template>
        <template #articleStatus_default="{ row }">
          <zh-badge color="yellow" :text="row.articleStatusName" v-if="row.articleStatus === 'draft'" />
          <zh-badge color="pink" :text="row.articleStatusName" v-if="row.articleStatus === 'auth'" />
          <zh-badge status="success" :text="row.articleStatusName" v-if="row.articleStatus === 'finish'" />
          <zh-badge status="processing" :text="row.articleStatusName" v-if="row.articleStatus === 'on'" />
          <zh-badge status="default" :text="row.articleStatusName" v-if="row.articleStatus === 'off'" />
        </template>
				<template #operate_default="{ row }">
            <el-tooltip
            effect="dark"
            content="查看详情"
            placement="top"
          >
            <zh-button v-func:article0002 button-type="query" link @click="queryDetail(row)"></zh-button>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="修改信息"
            v-if="state.superAdmin||row.articleStatus==='draft'"
            placement="top"
          >
            <zh-button v-func:article0005 button-type="edit" link @click="editArticle(row)"></zh-button>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="提交审核"
            v-if="row.articleStatus==='draft'"
            placement="top"
          >
            <zh-button v-func:article0009 icon="ele-Select" link @click="submitAuth(row)"></zh-button>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            :content="row.articleStatus==='on'?'下架':'上架'"
            placement="top"
            v-if="(row.articleStatus==='finish'||row.articleStatus==='on'||row.articleStatus==='off')&&row.authStatus==='1'"
          >
            <zh-button v-func:article0008 :icon="row.articleStatus==='on'?'ele-Bottom':'ele-Top'" link @click="editPublish(row)"></zh-button>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="退回到草稿"
            v-if="row.articleStatus!=='on'&&row.articleStatus!=='draft'"
            placement="top"
          >
            <zh-button v-func:article0011 icon="ele-RefreshLeft" link @click="backDraft(row)"></zh-button>
          </el-tooltip>
          <el-tooltip
            v-if="row.articleStatus==='auth'"
            effect="dark"
            content="审核"
            placement="top"
          >
            <zh-button v-func:article0010 icon="ele-Coordinate" link @click="openAuh(row)"></zh-button>
          </el-tooltip>
          <el-popconfirm v-if="row.articleStatus!=='on'" title="是否确认删除?" @confirm="delArticle(row)">
            <template #reference>
              <zh-button type="danger" v-func:article0006 button-type="del" link ></zh-button>
            </template>
          </el-popconfirm>
          </template>
			</zh-table>
		</zh-space>
		<zh-dialog :title="state.modalTitle" width="85%" v-model="state.visible"  >
			<ArticleForm ref="articlePage" :showFlag="state.showFlag" :articleInfo="state.selectData" v-model="state.visible" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onClose">{{state.showFlag?'关闭':'取消'}}</el-button>
          <el-button v-if="!state.showFlag" type="primary" @click="saveArticle">
            保存
          </el-button>
        </span>
      </template>
		</zh-dialog>
    <zh-dialog title="审核" width="45%" v-model="state.authVisible" @confirm="auth">
			<zh-form ref="articleAuthFormRef" :span="24" :model="state.authForm" :rules="state.authRules">
        <zh-form-select  prop="authStatus" label="审核状态" :options="state.authDict" v-model="state.authForm.authStatus"></zh-form-select>
        <zh-form-input
          :span="24"
          :rows="4"
          prop="authRemarks"
          type="textarea"
          label="审核意见"
          v-model="state.authForm.authRemarks"
        ></zh-form-input>
      </zh-form>
		</zh-dialog>
	</div>
</template>

<script lang="ts" setup name="articleManager">
import {ElMessageBox,ElMessage } from 'element-plus'
import ArticleForm from './component/ArticleForm.vue';

//------------------定义子组件---------------------------
const articleQueryForm = ref<any>({});
const articleListTable = ref<any>({});
const articlePage = ref<any>({});
const articleAuthFormRef=ref<any>();
//------------------内部变量定义-------------------------
const state = reactive({
	description: '系统状态通知管理',
	dictData: {} as any,
  areaCodeSelectTreeData:[],
	visible: false,
  articleTypeDisabled:false,
  authVisible:false,
	form: null,
	// 高级搜索 展开/关闭
	advanced: false,
  superAdmin:false,
	// 查询参数
	queryParam: {
		paramKey: undefined,
		paramName: undefined,
		paramValue: undefined,
		status: undefined,
		fixed: undefined,
    showPosition:"20",
    articleType:"",

	} as any,
  authDict:[{dictKey:'1',dictValue:'审核通过'},{dictKey:'2',dictValue:'审核不通过'}],
	// 表头
	loading: false,
	tablePage: {
		total: 0,
		currentPage: 1,
		pageNum: 1,
		pageSize: 20,
	},
	tableColumn: [
		{ type: 'seq', width: 80, fixed: 'left', align: 'center', title: '序号' },
		{ field: 'articleId', title: '文章id', visible: false, fixed: 'left', align: 'center', width: 150 },
		{ field: 'title', title: '标题', align: 'center', fixed: 'left', width: 250 },
		{ field: 'shortTitle', title: '标题简称', align: 'center', width: 250 },
		{
			field: 'articleStatus',
			title: '状态',
			align: 'center',
			width: 120,
			slots: {
				default: 'articleStatus_default',
      }
		},
    { field: 'publishTime', title: '发布时间', align: 'center', width: 200 },
    { field: 'offTime', title: '下架时间', align: 'center', width: 200 },
    { field: 'publisher', title: '发布主体（人或单位）', align: 'center', width: 250 },
		{
			field: 'authStatus',
			title: '审核状态',
			align: 'center',
			width: 150,
			slots: {
				default:'authStatus_default'
			},
		},
		{ field: 'authRemarks', title: '审核说明', align: 'center', width: 350 },
		{ field: 'authTime', title: '审核时间', align: 'center', width: 200 },
		{ field: 'linkTypeName', title: '链接类型', align: 'center', width: 150 },
		{ field: 'linkUrl', title: '链接地址', align: 'center', width: 150 },
    { field: 'linkPath', title: '内部路由路径', align: 'center', width: 150 },
    { field: 'linkName', title: '内部路由名', align: 'center', width: 150 },
    { field: 'linkParams', title: '链接参数', align: 'center', width: 150 },
		{ field: 'orgName', title: '所属组织', align: 'center', width: 250 },
    { field: 'areaName', title: '行政区划名称', align: 'center', width: 250 },
    { field: 'appName', title: '所属应用', align: 'center', width: 250 },
		{ field: 'remarks', title: '备注', align: 'center', showOverflow: true, width: 350 },
    { field: 'operate', title: '操作', align: 'center',fixed: 'right',  width: 220,slots: {default: 'operate_default'}},
	],
	modalTitle: '操作',
	selectData: {} as any,
  showFlag:false,
  authForm:{} as any,
  authRules: {
		authStatus: [
			{
				required: true,
				message: '请选择审核状态',
				trigger: 'blur',
			},
		],
	},
});

//------------------定义调用方法-------------------------
function addArticle() {
	state.modalTitle = '新增';
	state.selectData = {};
  state.showFlag=false
	state.visible = true;
}
function queryDetail(row) {
  state.modalTitle = '查看详情';
	state.selectData=row
  state.showFlag=true
  state.visible = true;
}
function editArticle(row) {
	state.modalTitle = '修改';
	state.selectData=row
  state.showFlag=false
  state.visible = true;
}
const onClose=()=>{
  state.visible = false;
}
function saveArticle() {
	articlePage.value.save().then(() => {
		articleListTable.value.refresh(state.queryParam);
	});
}
function openAuh(row){
  let params={articleId:row.articleId}
  state.authForm=params
  state.authVisible=true
}
async function auth(){
  //审核
  let checkFlag = await articleAuthFormRef.value.checkForm();
	if (checkFlag) {
		$api.common.send.post('article0010', state.authForm).then(() => {
      ElMessage.success('审核成功！');
      state.authVisible=false
      articleListTable.value.refresh(state.queryParam);
    });
	}
}
function submitAuth(row){
  //提交审核
  ElMessageBox.confirm(
    '是否确认提交审核?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  ).then(() => {
    //调用方法
    let params={articleId:row.articleId}
    $api.common.send.post('article0009', params).then(() => {
      ElMessage.success('提交成功！');
      articleListTable.value.refresh(state.queryParam);
    });
  })
  .catch(() => {
      
  })
}
function editPublish(row){
  //上下架
  let message="上架"
  let articleStatus="on"
  if(row.articleStatus==='on'){
    message="下架"
    articleStatus='off'
  }
  ElMessageBox.confirm(
    '是否确认'+message+'?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  )
  .then(() => {
    //调用方法
    let params={articleId:row.articleId,articleStatus:articleStatus}
    $api.common.send.post('article0008', params).then(() => {
      ElMessage.success('操作成功！');
      articleListTable.value.refresh(state.queryParam);
    });
  })
  .catch(() => {
     
  })
}
function backDraft(row){
  //退回到草稿状态
  ElMessageBox.confirm(
    '是否确认回退到草稿状态?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  )
  .then(() => {
    //调用方法
    let params={articleId:row.articleId}
    $api.common.send.post('article0011', params).then(() => {
      ElMessage.success('退回成功！');
      articleListTable.value.refresh(state.queryParam);
    });
  })
  .catch(() => {
     
  })
}

function delArticle(row) {
	let params={articleId:row.articleId}
	setTimeout(() => {
		$api.common.send
			.post('article0006', params)
				.then(() => {
					$messageBox.success('删除成功', '成功提示');
					articleListTable.value.refresh(state.queryParam);
				})
				.catch(() => {});
	}, 20);
	
}
function getAreaCodeData() {
	setTimeout(() => {
		$api.common.send.post('dict0026', {}).then((res) => {
			state.areaCodeSelectTreeData = res.result;
      state.queryParam.areaCode=$store.user.userInfo?.areaCode
		});
	}, 20);
}

//------------------初始化------------------------------
const params = {
	dictFields: 'ARTICLESTATUS,authStatus,articleType,showPosition,flag,fileType,contentType',
};
$api.common.getBatchDict.post(params).then((res) => {
	state.dictData = res.result;
});
onMounted(() => {
  let systemPrivileges = $store.user.systemPrivileges;
  if (systemPrivileges && systemPrivileges.indexOf('SUPERADMIN') >= 0) {
		state.superAdmin=true;
	}else{
    state.superAdmin=false;
  }
  getAreaCodeData();
  //获取路由配置中param1参数
  let meta = useRouter().currentRoute.value.meta;
  const query: any = meta.query;
  state.queryParam.articleType = query.articleType;
  if(query.articleType){
    state.articleTypeDisabled=true;
  }else{
    state.articleTypeDisabled=false;
  }
  articleListTable.value.query(state.queryParam);
  
  
});
</script>
